package com.ruoyi.edh.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;


import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.NumberingGetUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.edh.dao.GoodsDetailDao;
import com.ruoyi.edh.domain.EdhGoods;
import com.ruoyi.edh.domain.EdhGoodsDetail;
import com.ruoyi.edh.domain.EdhGoodsSpecifications;
import com.ruoyi.edh.domain.EdhShoppingCart;
import com.ruoyi.edh.domain.dto.EdhAddGoodsDto;
import com.ruoyi.edh.domain.dto.EdhGoodsSpecificationsDto;
import com.ruoyi.edh.domain.dto.EdhSummaryGoodsDto;
import com.ruoyi.edh.domain.vo.EdhDetailsGoodsVo;
import com.ruoyi.edh.domain.vo.EdhSummaryGoodsListVo;
import com.ruoyi.edh.domain.vo.EdhSummaryGoodsVo;
import com.ruoyi.edh.mapper.EdhGoodsMapper;
import com.ruoyi.edh.mapper.EdhGoodsSpecificationsMapper;
import com.ruoyi.edh.service.IEdhGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 易订货-商品Service业务层处理
 *
 * @author xxx
 * @date 2020-09-02
 */
@Service
public class EdhGoodsServiceImpl implements IEdhGoodsService
{
    @Autowired
    private EdhGoodsMapper edhGoodsMapper;
    @Autowired
    private EdhGoodsSpecificationsMapper edhGoodsSpecificationsMapper;
    @Autowired
    private GoodsDetailDao goodsDetailDao;
    /**
     * 查询易订货-商品
     *
     * @param id 易订货-商品ID
     * @return 易订货-商品
     */
    @Override
    public EdhGoods selectEdhGoodsById(Long id)
    {
        EdhGoods edhGoods = edhGoodsMapper.selectEdhGoodsById(id);
        EdhGoodsDetail goodsDetail = goodsDetailDao.find(id);
        edhGoods.setDetails(goodsDetail.getDetails());
        return edhGoods;
    }

    /**
     * 根据部分dto中的字段查询商品的概要信息
     * @param edhSummaryGoodsDto
     * @return
     */
    @Override
    public List<EdhSummaryGoodsVo> selectSummaryGoodsList(EdhSummaryGoodsDto edhSummaryGoodsDto) {
        return edhGoodsMapper.selectSummaryGoodsList(edhSummaryGoodsDto);
    }

    @Override
    public EdhDetailsGoodsVo selectDetailsGoodsByid(String id) {
        EdhDetailsGoodsVo goods = edhGoodsMapper.selectDetailsGoodsByid(id);
        EdhGoodsDetail goodsDetail = goodsDetailDao.find(Long.valueOf(id));
        if (StringUtils.isNotNull(goodsDetail)){
            goods.setDetails(goodsDetail.getDetails());
        }
        return goods;
    }

    /**
     * @Author: 周爱鸿
     * @Description:更新mongo
     * @CreateDate: 2020/11/12 17:41
     */
    @Override
    public int updatemongo() {
        List<EdhGoodsDetail> edhGoodsDetails = edhGoodsMapper.allDetails();
        edhGoodsDetails.forEach(item->{
            goodsDetailDao.save(item);
        });
        return 0;
    }

    /**
     * 查询易订货-商品列表
     *
     * @param edhGoods 易订货-商品
     * @return 易订货-商品
     */
    @Override
    public List<EdhSummaryGoodsListVo> selectEdhGoodsList(EdhGoods edhGoods)
    {
        if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserConstants.SUPPLIER_USER)){
            edhGoods.setSupplierId(SecurityUtils.getUserId());
        }
        return edhGoodsMapper.queryEdhGoodsList(edhGoods);
    }

    /**
     * 新增易订货-商品
     *
     * @param edhGoods 易订货-商品
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertEdhGoods(EdhAddGoodsDto edhGoods)
    {
        Boolean add=true;
        //获取登陆用户信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        EdhGoods edhGoods1=new EdhGoods();
        edhGoods1.setCode(NumberingGetUtils.numberingGet("SP"));
        edhGoods1.setTitle(edhGoods.getTitle());
        edhGoods1.setImage(edhGoods.getImage());
        edhGoods1.setOnSale(edhGoods.getOnSale());
        edhGoods1.setStockUnit(edhGoods.getStockUnit());
        edhGoods1.setRemake(edhGoods.getRemake());
        edhGoods1.setRebate(edhGoods.getRebate());
        edhGoods1.setSupplierId(SecurityUtils.getUserId());
        edhGoods1.setCategoriesId(edhGoods.getCategoriesId());
        edhGoods1.setCreateTime(DateUtils.getNowDate());
        edhGoods1.setCreateBy(user.getUserId().toString());
        edhGoods1.setIsNew(1);
        edhGoods1.setIsReview(1);
        //判断是否是代理商添加商品如果是进入待审核状态
        if ("33".equals(user.getUserType())){
            edhGoods1.setIsReview(0);
        }

        int addGoods = edhGoodsMapper.insertEdhGoods(edhGoods1);

        // 插入详情
        EdhGoodsDetail detail = new EdhGoodsDetail();
        detail.setId(edhGoods1.getId());
        detail.setDetails(edhGoods.getDetails());
        goodsDetailDao.save(detail);

        if (addGoods<1){
            add=false;
        }
        //获取到商品规格对象
        EdhGoodsSpecificationsDto specifications = edhGoods.getSpecifications();
        for (int i = 0; i < edhGoods.getSpecifications().getObj().size(); i++) {
            EdhGoodsSpecifications edhGoodsSpecifications = specifications.getObj().get(i);
            edhGoodsSpecifications.setGoodsId(edhGoods1.getId());
            edhGoodsSpecifications.setCreateBy(SecurityUtils.getUserId()+"");
            edhGoodsSpecifications.setCreateTime(DateUtils.getNowDate());
            int addGoodsSp = edhGoodsSpecificationsMapper.insertEdhGoodsSpecifications(edhGoodsSpecifications);
            if (addGoodsSp<1){
                add=false;
            }
        }

        return add;
    }

    /**
     * 修改易订货-商品
     *
     * @param edhGoods 易订货-商品
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateEdhGoods(EdhAddGoodsDto edhGoods)
    {
        Boolean update=true;
        //获取登陆用户信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        EdhGoods edhGoods1=new EdhGoods();
        edhGoods1.setId(edhGoods.getId());
        edhGoods1.setCode(NumberingGetUtils.numberingGet("SP"));
        edhGoods1.setTitle(edhGoods.getTitle());
        edhGoods1.setImage(edhGoods.getImage());
        edhGoods1.setOnSale(edhGoods.getOnSale());
        edhGoods1.setStockUnit(edhGoods.getStockUnit());
        edhGoods1.setRemake(edhGoods.getRemake());
        edhGoods1.setCategoriesId(edhGoods.getCategoriesId());
        edhGoods1.setRebate(edhGoods.getRebate());
        edhGoods1.setUpdateBy(user.getUserId().toString());
        edhGoods1.setIsReview(edhGoods.getIsReview());

        // 修改详情
        EdhGoodsDetail detail = new EdhGoodsDetail();
        detail.setId(edhGoods1.getId());
        detail.setDetails(edhGoods.getDetails());
        goodsDetailDao.update(detail);

        //判断是否是代理商添加商品如果是进入待审核状态
        if (UserConstants.SUPPLIER_USER.equals(user.getUserType())){
            edhGoods1.setIsReview(0);
        }

        int updateGoods = edhGoodsMapper.updateEdhGoods(edhGoods1);
        if (updateGoods<1){
            update=false;
        }
        EdhGoodsSpecifications goodsSpecifications=new EdhGoodsSpecifications();
        goodsSpecifications.setGoodsId(edhGoods1.getId());
        goodsSpecifications.setMarketPrice(edhGoods.getMarketPrice());
        goodsSpecifications.setUpdateBy(user.getUserId().toString());
        //获取到商品规格对象
        EdhGoodsSpecificationsDto specifications = edhGoods.getSpecifications();
        for (int i = 0; i < edhGoods.getSpecifications().getObj().size(); i++) {
            EdhGoodsSpecifications edhGoodsSpecifications = specifications.getObj().get(i);
            Long id = edhGoodsSpecifications.getId();
            Integer addGoodsSp=null;
            //如果商品规格id不存在就是新增，存在就是修改
            if (id==null){
                edhGoodsSpecifications.setCreateBy(SecurityUtils.getUserId().toString());
                edhGoodsSpecifications.setGoodsId(edhGoods.getId());
                edhGoodsSpecifications.setCreateTime(new Date());
                addGoodsSp=edhGoodsSpecificationsMapper.insertEdhGoodsSpecifications(edhGoodsSpecifications);
            }else {
                addGoodsSp= edhGoodsSpecificationsMapper.updateEdhGoodsSpecifications(edhGoodsSpecifications);
            }

            if (addGoodsSp<1){
                update=false;
            }
        }
    	// 如果是下架操作  则是购物车失效
    	if (StringUtils.isNotNull(edhGoods.getOnSale()) && 0 == edhGoods.getOnSale()){
    		EdhShoppingCart.killGoodsByGoodsId(edhGoods.getId());
		}

        return update;
    }
    /**
     *
     *
     * @description: 修改商品的基本信息
     * @param edhGoods
     * @return: Integer
     * @author: 梁东宸
     * @time: 2020/9/24 2:11 下午
     */
    @Override
    public Integer updateEdhGoodsState(EdhGoods edhGoods) {
        if (StringUtils.isNotNull(edhGoods.getId())){
            // 修改详情
            EdhGoodsDetail detail = new EdhGoodsDetail();
            detail.setId(edhGoods.getId());
            detail.setDetails(edhGoods.getDetails());
            goodsDetailDao.update(detail);
        }
        return edhGoodsMapper.updateEdhGoods(edhGoods);
    }

    /**
     * 批量删除易订货-商品
     *
     * @param ids 需要删除的易订货-商品ID
     * @return 结果
     */
    @Override
    public int deleteEdhGoodsByIds(Long[] ids)
    {
    	// 使购物车失效
    	for (Long id : ids){
			EdhShoppingCart.killGoodsByGoodsId(id);
		}

        return edhGoodsMapper.deleteEdhGoodsByIds(ids);
    }

    /**
     * 批量修改上架状态
     * @param ids
     * @return
     */
    @Override
    public Integer editOnsale(Long[] ids,String onSale) {
        return edhGoodsMapper.editOnsale(ids,onSale);
    }

    /**
     * 删除易订货-商品信息
     *
     * @param id 易订货-商品ID
     * @return 结果
     */
    @Override
    public int deleteEdhGoodsById(Long id)
    {
        return edhGoodsMapper.deleteEdhGoodsById(id);
    }

    /**
     * 获取首页商品总览数据
     */
    @Override
    public Map<String, Object> getProductOverview() {
        Long userId= SecurityUtils.getUserId();
        return edhGoodsMapper.getProductOverview(userId);
    }

    /**
     * 获取根据分类的商品tree
     */
    @Override
    public Map<String, Object> getGoodsTree(Long scheduledId) {
        // 获取商品
        Map<String,Object> result = new HashMap<String, Object>(16);
        List<Map<String, Object>> categories = edhGoodsMapper.getCategoriesHasGoods();
        List<Map<String, Object>> goods = edhGoodsMapper.selectAll();
        for (Map<String,Object> map :categories){
            List<Map<String,Object>> list = new LinkedList<Map<String, Object>>();
            for (Map<String,Object> goodsmap : goods){
                if (map.get("id").equals(goodsmap.get("pid"))){
                    list.add(goodsmap);
                }
            }
            map.put("children",list);
        }

        // 获取已经选择的商品id
        if (StringUtils.isNotNull(scheduledId)){
            result.put("scheduledGoods",edhGoodsMapper.selectGoodsIdByScheduledId(scheduledId));
        }
        result.put("goodsTree",categories);
        return result;
    }
}
